<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const jsonp = ({url, params, callbackNmae}) => {
      const generateURL = () => {
        let dataStr = ''
        for (let key in params) {
          dataStr += `${key}=${params[key]}&` // name='格格'&age=18&
        }
        dataStr += `callback=${callbackNmae}` // name='格格'&age=18&callback=getData
        return `${url}?${dataStr}`
      }

      return new Promise((resolve, reject) => {
        callbackNmae = callbackNmae || 'cb' + Math.random().toString().replace('.', '')
        let script = document.createElement('script')
        script.src = generateURL()
        document.body.appendChild(script)

        window[callbackNmae] = data => {
          resolve(data)
          document.body.removeChild(script)
        }
      })
    }

    // <script src="http://loalhost:3000?name='格格'&age=18&callback=getData" />
    jsonp({
      url: 'http://localhost:3000',
      params: {
        name: '格格',
        age: 18
      },
      callbackName: 'getData'
    }) 
    .then(data => JSON.parse(data))
    .then(data =>  {
      console.log(data);
    })
  </script>
</body>
</html>
